package top.huhuiyu.study.servlet.dept;

import top.huhuiyu.study.dao.TbDeptDAO;
import top.huhuiyu.study.entity.Result;
import top.huhuiyu.study.entity.TbDept;
import top.huhuiyu.study.util.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "deptQueryByIdServlet", urlPatterns = "/dept/querybyid.action")
public class QueryByIdServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        try {
            Integer id = Integer.parseInt(req.getParameter("id"));
            TbDept dept = TbDeptDAO.queryById(id);
            if (dept == null) {
                Result<String> result = Result.fail("部门不存在", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            Result<TbDept> result = Result.success("查询成功", dept);
            writer.println(JsonUtils.stringify(result));
        } catch (Exception e) {
            e.printStackTrace();
            Result<String> result = Result.fail("添加发生错误", null);
            writer.println(JsonUtils.stringify(result));
        }

    }
}
